# @before-stub-for-debug-begin
from python3problem637 import *
from typing import *
# @before-stub-for-debug-end

#
# @lc app=leetcode.cn id=637 lang=python3
#
# [637] 二叉树的层平均值
#

class TreeNode:
    def __init__(self, val=0, left=None, right=None):
        self.val = val
        self.left = left
        self.right = right
import collections
from typing import List, Optional
# @lc code=start
# Definition for a binary tree node.



class Solution:
    def averageOfLevels(self, root: Optional[TreeNode]) -> List[float]:
        if root is None:
            return []
        queue = collections.deque()
        queue.append(root)
        ans = []
        while queue:
            bak_size = size = len(queue)
            sum_val = 0
            while size > 0:
                size -= 1
                node = queue.popleft()
                sum_val += node.val
                if node.left:
                    queue.append(node.left)
                if node.right:
                    queue.append(node.right)
            ans.append(sum_val/bak_size)
        return ans
# @lc code=end

